import React, {Component} from 'react';
import {UploadOutlined} from '@ant-design/icons';
import {Button, Input, Select, Upload, Form, message, DatePicker, Row, Col, Radio} from 'antd';
import {connect, FormattedMessage, formatMessage} from 'umi';
import {CurrentUser} from '../data.d';
import GeographicView from './GeographicView';
import styles from './BaseView.less';
import {FormInstance} from 'antd/lib/form';
import {updateUser} from "../service";
import moment from 'moment';
import {Dispatch} from "@@/plugin-dva/connect";


const {Option} = Select;

// 头像组件 方便以后独立，增加裁剪之类的功能
const AvatarView = ({avatar}: { avatar: string }) => (
  <>
    <div className={styles.avatar_title}>
      <FormattedMessage id="accountandsettings.basic.avatar" defaultMessage="Avatar"/>
    </div>
    <div className={styles.avatar}>
      <img src={avatar} alt="avatar"/>
    </div>
    <Upload showUploadList={false}>
      <div className={styles.button_view}>
        <Button>
          <UploadOutlined/>
          <FormattedMessage
            id="accountandsettings.basic.change-avatar"
            defaultMessage="Change avatar"
          />
        </Button>
      </div>
    </Upload>
  </>
);

interface SelectItem {
  label: string;
  key: string;
}

interface BaseViewProps {
  currentUser?: CurrentUser;
  dispatch: Dispatch;
}


/**
 * 更新
 * @param fields
 */
const handleUpdateUser = async (fields: CurrentUser) => {
  const hide = message.loading('正在更新');
  try {
    const data = await updateUser({...fields});
    hide();
    if (data.code === 1) {
      message.success('更新用户信息成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('更新用户信息失败,请重试');
    return false;
  }
  message.error('更新用户信息失败,请重试');
  return false;
};


class BaseView extends Component<BaseViewProps> {
  view: HTMLDivElement | undefined = undefined;

  formRef = React.createRef<FormInstance>();

  componentDidMount() {
    const {dispatch} = this.props;
    if (dispatch) {
      dispatch({
        type: 'accountAndsettings/fetchCurrent',
        callback: (response: any) => {
          this.formRef.current!.setFieldsValue(response);
        },
      });
    }
  }

  getAvatarURL() {
    const {currentUser} = this.props;
    if (currentUser) {
      if (currentUser.headHeadPath) {
        return currentUser.headHeadPath;
      }
      const url = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
      return url;
    }
    return '';
  }

  getViewDom = (ref: HTMLDivElement) => {
    this.view = ref;
  };


  handleFinish = (values: CurrentUser) => {
    if (values.birth !== undefined && values.birth !== null) {
      values.birth = moment(values.birth).format("YYYY-MM-DD");
    }
    values.province = values.geographic.province.key;
    values.city = values.geographic.city.key;
    delete values.geographic;
    handleUpdateUser(values);
  };


  render() {
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form
            layout="vertical"
            ref={this.formRef}
            onFinish={this.handleFinish}
            hideRequiredMark
          >

            <Row gutter={24}>
              <Col span={12}>

                <Form.Item
                  name="name"
                  label={formatMessage({id: 'accountandsettings.basic.name'})}
                  rules={[
                    {
                      required: true,
                      message: formatMessage({id: 'accountandsettings.basic.name-message'}, {}),
                    },
                  ]}
                >
                  <Input/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="nickName"
                  label={formatMessage({id: 'accountandsettings.basic.nickName'})}
                >
                  <Input placeholder={formatMessage({id:'accountandsettings.basic.nickName-placeholder'})}/>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="email"
              label={formatMessage({id: 'accountandsettings.basic.email'})}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'accountandsettings.basic.email-message'}, {}),
                },
              ]}
            >
              <Input/>
            </Form.Item>

            <Form.Item
              name="phone"
              label={formatMessage({id: 'accountandsettings.basic.phone'})}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'accountandsettings.basic.phone-message'}, {}),
                },
              ]}
            >
              <Input/>
            </Form.Item>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="birth"
                  label={formatMessage({id: 'accountandsettings.basic.birth'})}
                >
                  <DatePicker/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="sex"
                  label={formatMessage({id: 'accountandsettings.basic.sex'})}
                >
                  <Radio.Group>
                    <Radio value={0}>男</Radio>
                    <Radio value={1}>女</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>


            <Form.Item
              name="country"
              label={formatMessage({id: 'accountandsettings.basic.country'})}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'accountandsettings.basic.country-message'}, {}),
                },
              ]}
            >
              <Select>
                <Option value={0}>中国</Option>
              </Select>
            </Form.Item>


            <Form.Item
              name="geographic"
              label={formatMessage({id: 'accountandsettings.basic.geographic'})}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'accountandsettings.basic.geographic-message'}, {}),
                },
                {
                  validator: async (rule, value: { province: SelectItem; city: SelectItem; }) => {
                    const {province, city} = value;
                    if (!province.key) {
                      throw new Error('请选择省!');
                    }
                    if (!city.key) {
                      throw new Error('请选择城市!');
                    }
                  }
                },
              ]}
            >
              <GeographicView/>
            </Form.Item>

            <Form.Item
              name="address"
              label={formatMessage({id: 'accountandsettings.basic.address'})}
            >
              <Input placeholder={formatMessage({id:'accountandsettings.basic.address-placeholder'})}/>
            </Form.Item>

            <Form.Item
              name="signature"
              label={formatMessage({id: 'accountandsettings.basic.signature'})}
            >
              <Input placeholder={formatMessage({id:'accountandsettings.basic.signature-placeholder'})}/>
            </Form.Item>

            <Form.Item
              name="introduction"
              label={formatMessage({id: 'accountandsettings.basic.introduction'})}
            >
              <Input.TextArea
                placeholder={formatMessage({id: 'accountandsettings.basic.introduction-placeholder'})}
                rows={4}
              />
            </Form.Item>

            <Form.Item>
              <Button htmlType="submit" type="primary">
                <FormattedMessage
                  id="accountandsettings.basic.update"
                  defaultMessage="Update Information"
                />
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className={styles.right}>
          <AvatarView avatar={this.getAvatarURL()}/>
        </div>
      </div>
    );
  }
}

export default connect(
  ({accountAndsettings}: { accountAndsettings: { currentUser: CurrentUser } }) => ({
    currentUser: accountAndsettings.currentUser,
  }),
)(BaseView);
